package com.example.administrator.smartdevice.serial;

import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.example.administrator.smartdevice.event.MessageEvent;
import com.example.administrator.smartdevice.model.FunctionModel;
import com.example.administrator.smartdevice.model.FunctionModelExt;
import com.example.administrator.smartdevice.utils.AppApplication;
import com.topeet.serialtest.serial;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/4/24.
 */

public class SerialPortManager {
    private static final String TAG = "hhc";
    private static SerialPortManager serialPortManager = null;
    private SerialListenerThread serialListenerThread = null;
    private boolean threadStatus = false;//监控线程状态
    public boolean serialPortStatus = false; //是否打开串口标志
    private serial mySerial;
    public String  result="";
    private SerialPortManager() {
        init();
    }

    public static SerialPortManager getInstance() {
        if (serialPortManager == null) {
            serialPortManager = new SerialPortManager();
        }
        return serialPortManager;
    }

    public void init() {
        openSerialPort();
    }

    class SerialListenerThread extends Thread {
        public void run() {
            while (!threadStatus) {
                int[] in = mySerial.Read();
                if (in != null && in.length > 0) {
                    result = result+intToString(in);
                    if(in[in.length-1]==10) {
                        Log.d(TAG, "run: "+result);
                        String[] s = result.split("_");
                        if (s.length == 5) {
                            MessageEvent messageEvent = new MessageEvent();
                            messageEvent.setOperationType(s[0]);
                            messageEvent.setApplianceId(s[1]);
                            messageEvent.setApplianceType(s[2]);
                            messageEvent.setStatus(s[3]);
                            messageEvent.setParams(s[4]);
                            EventBus.getDefault().post(messageEvent);
                        } else {
                            Log.d(TAG, "run: 参数长度不等于5");
                        }
                        result="";
                    }
                }
            }
        }
    }



    //线程控制
    public void setThreadStatus(boolean threadStatus) {
        this.threadStatus = threadStatus;
    }

    //打开端口
    public void openSerialPort() {
        if (mySerial == null) {
            mySerial = new serial();
        }
        if (mySerial != null) {
            int fd = mySerial.Open(3, 115200);
            //打开失败时返回-1
            if (fd == -1) {
                mySerial = null;
                Toast.makeText(AppApplication.getContext(), "串口打开异常", Toast.LENGTH_LONG).show();
            } else {
                this.serialPortStatus = true;
                this.threadStatus = false;
                //开启线程监控
                serialListenerThread = new SerialListenerThread();
                serialListenerThread.start();
            }
        }
    }

    //关闭端口
    public void closeSerialPort() {
        this.serialPortStatus = false;
        this.threadStatus = true; //线程状态
        int fd = mySerial.Close();
        //不清楚返回值
        if (fd == -1) {

        }
    }

    //发送数据
    public void sendData(String operation,String applianceId, String applianceType, String status, String params) {
        //操作类型_设备ID_设备类型_开关状态_params
        CharSequence tx = operation+"_" + applianceId + "_" + applianceType + "_" + status + "_" + params;
        int[] text;
        text = new int[tx.length()];
        for (int i = 0; i < tx.length(); i++) {
            text[i] = tx.charAt(i);
        }
        int fd = mySerial.Write(text, tx.length());
        if (fd == -1) {
            Toast.makeText(AppApplication.getContext(), "操作失败", Toast.LENGTH_LONG).show();
            //相关的家电状态回滚
        } else {
            //发送成功
            //保存家电id和家电
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
////                    isExit = false;
//                }
//            }, 2000);
        }
    }

    public void contrlHard(String applianceType, String status) {
        //10:电灯 20：门锁： 30：窗帘 50：空调 40：电视
        //10：开 20：关
        CharSequence tx = " ";
        int[] text;
        int i;
        if (applianceType.equals("10")) {
            if (status.equals("10")) {
                tx = "3q";
            } else if (status.equals("20")) {
                tx = "3w";
            }
        } else if (applianceType.equals("20")) {
            if (status.equals("10")) {
                tx = "3o";
            } else if (status.equals("20")) {
                tx = "3f";
            }
        } else if (applianceType.equals("30")) {
            if (status.equals("10")) {
                tx = "2o";
            } else if (status.equals("20")) {
                tx = "2f";
            }
        } else if (applianceType.equals("50")) {
            if (status.equals("10")) {
                tx = "1o";
            } else if (status.equals("20")) {
                tx = "1f";
            }
        } else if (applianceType.equals("40")) {
            if (status.equals("10")) {
                tx = "1k";
            } else if (status.equals("20")) {
                tx = "1g";
            }
        } else {
            tx = " ";
        }

        text = new int[tx.length()];
        for (i = 0; i < tx.length(); i++) {
            text[i] = tx.charAt(i);
        }

        if (mySerial != null) {
            mySerial.Write(text, tx.length());
        }
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);
    }

    //int数组转字符串
    public String intToString(int[] in) {
        char[] c = new char[in.length];
        for (int i = 0; i < in.length; i++) {
            c[i] = (char) in[i];
        }
        return String.valueOf(c);
    }
}
